import { Inject, Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { User } from './user.model';
import { Op } from 'sequelize';
import { CacheService } from 'src/cache/cache.service';
import { ConfigService } from '@nestjs/config';
import { verify } from 'jsonwebtoken';
@Injectable()
export class UserService {
  constructor(
    @Inject('UserRepository')
    private readonly userRepository: typeof User,
    private readonly cacheService: CacheService,
    private readonly configService: ConfigService,
  ) {}

  async findOne(username: string): Promise<any> {
    const user = await this.userRepository.findOne({
      where: { username },
    });
    if (user) {
      const { ...result } = user;
      return result;
    }
  }

  async findUserById(id: string): Promise<any> {
    const user = await this.userRepository.findOne({
      where: { id },
      attributes: { exclude: ['password'] },
    });
    if (user) {
      return { data: user };
    }
  }

  async create(data: CreateUserDto): Promise<any> {
    const { username, email, phone } = data;
    const userInfo = await this.userRepository.findOne({
      where: {
        [Op.or]: [{ username }, { email }, { phone }],
      },
    });
    if (userInfo) {
      if (userInfo.username === username) {
        return {
          code: -1,
          msg: '用户名已存在',
        };
      }
      if (userInfo.phone === phone) {
        return {
          code: -1,
          msg: '手机号已存在',
        };
      }
      if (userInfo.email === email) {
        return {
          code: -1,
          msg: '邮箱已存在',
        };
      }
    }
    const user = { ...data, create_time: new Date(), update_time: new Date() };
    const newUser = await this.userRepository.create(user);
    await newUser.save();
    return { msg: '注册成功' };
  }

  async logout(req: any) {
    let userInfo;
    const jwt = this.configService.get('jwt');
    if (req.headers.authorization) {
      userInfo = verify(req.headers.authorization.slice(7), jwt.secret);
      if (userInfo) {
        await this.cacheService.del(`access_token_${userInfo.id}`);
        await this.cacheService.del(`refresh_token_${userInfo.id}`);
      }
    }
    return { msg: '退出登录成功' };
  }
}
